<script setup>
import {
  getDetailAPI,
  getProductSpecsAPI,
  getProductImagesAPI,
  getBrandAPI
} from '@/apis/detail'
import { ref, nextTick } from 'vue'
import { useRoute } from 'vue-router'
// import GoodsSku from '@/components/GoodsSku.vue'
import { useCartStore } from '@/stores/index'
import GoodsHot from '@/views/Detail/components/GoodsHot.vue'
import { ElMessage } from 'element-plus'
// import GoodsImage from '@/components/GoodsImage.vue'
const childRef = ref(null)
// 获取商品详情
const route = useRoute()

const good = ref({
  id: '',
  name: '', // productName
  desc: '', // description
  price: 0, // price
  oldPrice: 0, // oldPrice
  mainPictures: [], // picture
  inventory: 0, // inventory
  salesCount: 0, // sales
  collectCount: 0, // totalPopularity
  categories: [], // categoryId (如果需要)
  commentCount: 0, // 评论数量
  brand: { name: '' }, // 品牌信息
  details: { properties: [] } // 商品详情
})

// 获取商品图片
const getProductImages = async () => {
  try {
    const res = await getProductImagesAPI(route.params.id)
    if (res.code === 200) {
      // 按照 sortOrder 排序图片
      const sortedImages = res.data.sort((a, b) => a.sortOrder - b.sortOrder)
      // 将排序后的图片 URL 追加到 mainPictures
      good.value.mainPictures.push(
        ...sortedImages.map((image) => image.pictureUrl)
      )
    } else {
      console.warn('未能成功获取商品图片')
    }
  } catch (error) {
    console.error('Error fetching product images:', error)
  }
}
// 获取商品详情的 API 调用
const getGoods = async () => {
  try {
    const res = await getDetailAPI(route.params.id)
    const data = res.data // API 返回的数据
    // 更新商品信息
    good.value = {
      id: data.id,
      name: data.productName,
      desc: data.description,
      price: data.price,
      oldPrice: data.oldPrice,
      mainPictures: [data.picture], // 只有一个主图，放入数组中
      inventory: data.inventory,
      salesCount: data.sales,
      collectCount: data.totalPopularity,
      categories: [data.categoryId], // 可能需要进一步处理多个分类
      commentCount: data.commentCount, // 评论数量
      brand: {
        name: data.brandName,
        id: data.brandId
      }, // 品牌名称
      details: { properties: data.properties || [] } // 商品属性
    }
    // 调用获取品牌详情的函数
    const brandRes = await getBrandAPI(data.brandId)
    if (brandRes && brandRes.data) {
      // 如果品牌信息返回成功，更新品牌信息
      good.value.brand.name = brandRes.data.name
    }
    //调用获取图片的函数
    await getProductImages()
  } catch (error) {
    console.error('Error fetching goods:', error)
  }
}
getGoods()

// 获取商品规格和规格值
const skuObj = ref({
  specs: [],
  selected: {}, // 用于记录已选的规格 {规格ID: 值ID}
  specsText: '',
  skuId: null // 用于记录选中的skuId
})
const number = ref([])
const selectSpec = (specId, valueId) => {
  number[specId] = 1
  skuObj.value.selected[specId] = valueId
  updateSpecsText()
  // 查找选中的规格值对象
  const selectedSpec = skuObj.value.specs.find((spec) => spec.id === specId)
  const selectedValue = selectedSpec?.values.find(
    (value) => value.id === valueId
  )

  // 如果有图片，存储或执行其他操作
  if (selectedValue && selectedValue.picture) {
    // 这里存储图片 URL 或者进行其他操作
    skuObj.value.selectedImage = selectedValue.picture
    // 使用箭头函数查找选中的图片索引
    const selectedImageIndex = good.value.mainPictures.findIndex(
      (picture) => picture === skuObj.value.selectedImage
    )
    // 确保子组件已渲染，使用 nextTick
    nextTick(() => {
      if (childRef.value) {
        childRef.value.mouseEnterFn(selectedImageIndex)
        console.log(selectedImageIndex)
      }
    })
  } else {
    skuObj.value.selectedImage = null // 没有图片时清空
  }
}
const updateSpecsText = () => {
  const selectedNames = skuObj.value.specs
    .map((spec) => {
      const valueId = skuObj.value.selected[spec.id]
      const selectedValue = spec.values.find((value) => value.id === valueId)
      return selectedValue ? `${spec.name}: ${selectedValue.name}` : null
    })
    .filter(Boolean)
  skuObj.value.specsText = selectedNames.join(', ')
}

// 获取商品规格 API
const getProductSpecs = async () => {
  try {
    const res = await getProductSpecsAPI(route.params.id)
    const specData = res.data

    // 解析规格数据
    const specs = Object.entries(specData).map(([key, values]) => {
      const match = key.match(/name=(.+?),/)
      return {
        id: key.match(/id=(\d+)/)?.[1],
        name: match?.[1],
        values: values.map((value) => ({
          id: value.id,
          name: value.name,
          picture: value.picture || null
        }))
      }
    })

    // 更新规格对象
    skuObj.value.specs = specs
    console.log('商品:', skuObj.value.specs)
    console.log('商品:', skuObj.value.specs.length)

    return specs // 返回解析后的规格
  } catch (error) {
    console.error('Error fetching product specs:', error)
    return null // 如果出错，返回 null
  }
}

// 调用获取规格 API，并打印规格信息
getProductSpecs().then((specs) => {
  if (specs) {
    console.log('商品规格:', specs)
  } else {
    console.warn('未能获取商品规格')
  }
})

// 加入购物车逻辑
const num = ref(1)
const countChange = (count) => {
  num.value = count
}

const cartStore = useCartStore()

import { useUserStore } from '@/stores/modules/user'
const userStore = useUserStore()
const add = async () => {
  //判断是否登录
  if (!userStore.userInfo.token) {
    return ElMessage.warning('请先登录')
  }
  for (let index = 0; index < skuObj.value.specs.length; index++) {
    if (number[skuObj.value.specs[index].id] != 1) {
      return ElMessage.warning('请选择' + skuObj.value.specs[index].name)
    }
  }
  const data = ref([])
  data.value[0] = {
    categoryId: good.value.categories[0],
    productId: good.value.id,
    productName: good.value.name,
    productPicture: good.value.mainPictures[0], // 确保传入第一张图片
    productPrice: good.value.price,
    productQuantity: num.value,
    attrsText: skuObj.value.specsText,
    selected: true
  }
  await cartStore.addCart(data)
}
</script>
<template>
  <div class="xtx-goods-page" v-if="good.name">
    <!-- 确保商品信息存在时才渲染页面 -->
    <div class="container">
      <div class="bread-container">
        <el-breadcrumb separator=">">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item
            :to="{ path: `/category/${good.categories?.[0]}` }"
            >分类</el-breadcrumb-item
          >
          <el-breadcrumb-item>{{ good.name }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 商品信息 -->
      <div class="info-container">
        <div>
          <div class="goods-info">
            <div class="media">
              <!-- 图片预览区 -->
              <goods-image
                :imageList="good.mainPictures"
                ref="childRef"
              ></goods-image>
              <!-- 统计数量 -->
              <ul class="goods-sales">
                <li>
                  <p>销量人气</p>
                  <p>{{ good.salesCount }}+</p>
                  <p><i class="iconfont icon-task-filling"></i>销量人气</p>
                </li>
                <li>
                  <p>商品评价</p>
                  <p>{{ good.commentCount }}+</p>
                  <p><i class="iconfont icon-comment-filling"></i>查看评价</p>
                </li>
                <li>
                  <p>收藏人气</p>
                  <p>{{ good.collectCount }}+</p>
                  <p><i class="iconfont icon-favorite-filling"></i>收藏商品</p>
                </li>
                <li>
                  <p>品牌信息</p>
                  <p>{{ good.brand.name }}</p>
                  <p><i class="iconfont icon-dynamic-filling"></i>品牌主页</p>
                </li>
              </ul>
            </div>
            <div class="spec">
              <!-- 商品信息区 -->
              <p class="g-name">{{ good.name }}</p>
              <p class="g-desc">{{ good.desc }}</p>
              <p class="g-price">
                <span>{{ good.price }}</span>
                <span> {{ good.oldPrice }}</span>
              </p>
              <div class="g-service">
                <dl>
                  <dt>促销</dt>
                  <dd>12月好物放送，App领券购买直降120元</dd>
                </dl>
                <dl>
                  <dt>服务</dt>
                  <dd>
                    <span>无忧退货</span>
                    <span>快速退款</span>
                    <span>免费包邮</span>
                    <a href="javascript:;">了解详情</a>
                  </dd>
                </dl>
              </div>
              <!-- SKU 选择组件 -->
              <div
                v-if="skuObj.specs && skuObj.specs.length > 0"
                class="sku-container"
              >
                <div
                  v-for="spec in skuObj.specs"
                  :key="spec.id"
                  class="sku-item"
                >
                  <p class="spec-name">{{ spec.name }}</p>
                  <div class="spec-values">
                    <el-button
                      v-for="value in spec.values"
                      :key="value.id"
                      :type="
                        skuObj.selected[spec.id] == value.id
                          ? 'primary'
                          : 'default'
                      "
                      @click="selectSpec(spec.id, value.id, value.name)"
                    >
                      <div class="spec-value">
                        <img
                          v-if="value.picture"
                          :src="value.picture"
                          class="spec-image"
                          alt="规格图片"
                        />
                        <span>{{ value.name }}</span>
                      </div>
                    </el-button>
                  </div>
                </div>
                <p>已选规格：{{ skuObj.specsText || '未选择规格' }}</p>
              </div>

              <!-- 数据组件 -->
              <el-input-number v-model="num" :min="1" @change="countChange" />
              <!-- 按钮组件 -->
              <div>
                <el-button size="large" class="btn" @click="add">
                  加入购物车
                </el-button>
              </div>
            </div>
          </div>
          <div class="goods-footer">
            <div class="goods-article">
              <!-- 商品详情 -->
              <div class="goods-tabs">
                <nav>
                  <a>商品详情</a>
                </nav>
                <div class="goods-detail">
                  <!-- 属性 -->
                  <ul class="attrs">
                    <li
                      v-for="item in good.details.properties"
                      :key="item.value"
                    >
                      <span class="dt">{{ item.name }}</span>
                      <span class="dd">{{ item.value }}</span>
                    </li>
                  </ul>
                  <div class="goods-aside">
                    <!-- 24小时热榜 -->
                    <goods-hot
                      :category-id="good.categories?.[0]"
                      :brand-id="good.brand?.id"
                    />
                  </div>
                  <!-- 图片 -->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.xtx-goods-page {
  .goods-info {
    min-height: 600px;
    background: #fff;
    display: flex;

    .media {
      width: 580px;
      height: 600px;
      padding: 30px 50px;
    }

    .spec {
      flex: 1;
      padding: 30px 30px 30px 0;
    }
  }

  .goods-footer {
    display: flex;
    margin-top: 20px;

    .goods-article {
      width: 940px;
      margin-right: 20px;
    }

    .goods-aside {
      width: 280px;
      min-height: 1000px;
    }
  }

  .goods-tabs {
    min-height: 600px;
    background: #fff;
  }

  .goods-warn {
    min-height: 600px;
    background: #fff;
    margin-top: 20px;
  }

  .number-box {
    display: flex;
    align-items: center;

    .label {
      width: 60px;
      color: #999;
      padding-left: 10px;
    }
  }

  .g-name {
    font-size: 22px;
  }

  .g-desc {
    color: #999;
    margin-top: 10px;
  }

  .g-price {
    margin-top: 10px;

    span {
      &::before {
        content: '¥';
        font-size: 14px;
      }

      &:first-child {
        color: $priceColor;
        margin-right: 10px;
        font-size: 22px;
      }

      &:last-child {
        color: #999;
        text-decoration: line-through;
        font-size: 16px;
      }
    }
  }

  .g-service {
    background: #f5f5f5;
    width: 500px;
    padding: 20px 10px 0 10px;
    margin-top: 10px;

    dl {
      padding-bottom: 20px;
      display: flex;
      align-items: center;

      dt {
        width: 50px;
        color: #999;
      }

      dd {
        color: #666;

        &:last-child {
          span {
            margin-right: 10px;

            &::before {
              content: '•';
              color: $xtxColor;
              margin-right: 2px;
            }
          }

          a {
            color: $xtxColor;
          }
        }
      }
    }
  }

  .goods-sales {
    display: flex;
    width: 400px;
    align-items: center;
    text-align: center;
    height: 140px;

    li {
      flex: 1;
      position: relative;

      ~ li::after {
        position: absolute;
        top: 10px;
        left: 0;
        height: 60px;
        border-left: 1px solid #e4e4e4;
        content: '';
      }

      p {
        &:first-child {
          color: #999;
        }

        &:nth-child(2) {
          color: $priceColor;
          margin-top: 10px;
        }

        &:last-child {
          color: #666;
          margin-top: 10px;

          i {
            color: $xtxColor;
            font-size: 14px;
            margin-right: 2px;
          }

          &:hover {
            color: $xtxColor;
            cursor: pointer;
          }
        }
      }
    }
  }
}

.goods-tabs {
  min-height: 600px;
  background: #fff;

  nav {
    height: 70px;
    line-height: 70px;
    display: flex;
    border-bottom: 1px solid #f5f5f5;

    a {
      padding: 0 40px;
      font-size: 18px;
      position: relative;

      > span {
        color: $priceColor;
        font-size: 16px;
        margin-left: 10px;
      }
    }
  }
}

.goods-detail {
  padding: 40px;

  .attrs {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 30px;

    li {
      display: flex;
      margin-bottom: 10px;
      width: 50%;

      .dt {
        width: 100px;
        color: #999;
      }

      .dd {
        flex: 1;
        color: #666;
      }
    }
  }

  > img {
    width: 100%;
  }
}

.btn {
  margin-top: 20px;
}

.bread-container {
  padding: 25px 0;
}

.sku-container {
  margin-top: 20px;
}

.sku-item {
  margin-bottom: 10px;
}

.spec-values {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 5px;
  // 确保按钮的高度一致
  .el-button {
    margin-left: 0; // 确保内边距一致
  }
}

.spec-value {
  display: flex;
  align-items: center;
}

.spec-image {
  width: 28px;
  height: 28px;
  margin-right: 5px; /* 图片和文字之间的间距 */
  margin-left: -8px; /* 移除图片左侧的间距，确保贴着选择框左边 */
}

.el-button {
  padding: 10px; /* 确保按钮本身的内边距最小 */
  margin: 5px; /* 去除按钮外边距 */
}
.el-button--large {
  margin-top: 20px;
}
.el-input__wrapper {
  margin-top: 10px;
}
</style>
